package com.huitone.gddw.service.impl.business;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Service;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.druid.sql.visitor.functions.Length;
import com.huitone.gddw.dao.business.ISendSmDao;
import com.huitone.gddw.dao.entity.SendSm;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.business.ISendSmService;
import com.huitone.gddw.service.dto.SvrNodeDefDTO;
import com.huitone.gddw.service.dto.business.SendSmCountDTO;
import com.huitone.gddw.service.dto.business.SendSmDTO;
import com.huitone.gddw.service.system.IRoleService;
import com.huitone.gddw.utils.SysLoginUtil;
import com.sun.jndi.url.iiopname.iiopnameURLContextFactory;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * 短信发送记录 接口实现类
 * 
 * @author wuluodan
 *
 */
@Service
public class SendSmService implements ISendSmService {

	@Autowired
	private ISendSmDao sendSmDao;

	@Autowired
	private IRoleService roleService;

	@Override
	public QueryPage<SendSmDTO> selectPage(QueryPage<SendSm> page) {
		List<SendSmDTO> result = null;
		int totalCount = 0;

		Map<String, Object> map = page.getParams();
		map.put("userId", SysLoginUtil.getLoginUserId());
		map.put("start", (page.getPageNo() - 1) * page.getPageSize() + 1);
		map.put("end", page.getPageNo() * page.getPageSize());
		
		if(map.get("userNo")!=null&&!"".equals(map.get("userNo"))){
			if (((String) map.get("userNo")).length()==11) {
				map.put("fullUserNo", "yes");
			}
		}else {
			map.put("fullUserNo", "no");
		}
		
		Integer limitCount = null;
		if (map.get("limitCount") != null && !"".equals(map.get("limitCount").toString())) {
			limitCount = Integer.valueOf((String) map.get("limitCount"));
		}
		boolean b = false;
		if (limitCount != null && limitCount != -1) {
			map.put("limitCount", limitCount);
			b = true;
		}else{
			map.put("limitCount", page.getPageNo() * page.getPageSize());
		}

		if (roleService.isRootAcsFlag(SysLoginUtil.getLoginUserId())) {
			result = sendSmDao.selectRoot(map);
			 if (!b) {
			 totalCount = sendSmDao.countRoot(map);
			 }else{
			 totalCount = Integer.valueOf(result.size() == 0 ? "0" : result.get(0).getMaxCount());
			 }
		} else {
			result = sendSmDao.selectUnit(map);
			 if (!b) {
			 totalCount = sendSmDao.countUnit(map);
			 }else{
			 totalCount = Integer.valueOf(result.size() == 0 ? "0" : result.get(0).getMaxCount());
			 }
		}


		QueryPage<SendSmDTO> queryPage = new QueryPage<SendSmDTO>();
		queryPage.setResult(result);
		queryPage.setPageNo(page.getPageNo());
		queryPage.setPageSize(page.getPageSize());
		queryPage.setTotalCount(totalCount);
		return queryPage;
	}
	

	// 数据面板下方分页
	public QueryPage<SendSmCountDTO> CountPage(QueryPage<SendSmCountDTO> qp, int totalCount) {
		List<SendSmCountDTO> result = null;
		Map<String, Object> params = qp.getParams();
		params.put("start", (qp.getPageNo() - 1) * qp.getPageSize() + 1);
		params.put("end", (qp.getPageNo() - 1) * qp.getPageSize()
				+ qp.getPageSize());

		if (params.get("dateType") != null && params.get("dateType").equals("mm")) {
			result = sendSmDao.countPageMM(params);

		}
		
		
		if (params.get("dateType") != null && params.get("dateType").equals("dd")) {
		
			result = sendSmDao.countPageDD(params);
		}
		if (params.get("dateType") != null && params.get("dateType").equals("hh24")) {
			result = sendSmDao.countPageHH(params);

		}
		if (params.get("dateType") != null && params.get("dateType").equals("mi")) {
			result = sendSmDao.countPageMI(params);
		}

		QueryPage<SendSmCountDTO> queryPage = new QueryPage<>();
		queryPage.setResult(result);
		queryPage.setPageNo(qp.getPageNo());
		queryPage.setPageSize(qp.getPageSize());
		queryPage.setTotalCount(totalCount);
		return queryPage;
	}

	@Override
	public SendSmDTO getDetial(String recId) {
		return sendSmDao.selectByPrimaryKey(recId);
	}

	@Override
	public List<SendSmDTO> getRecord(Map<String, Object> params) {
		params.put("userId", SysLoginUtil.getLoginUserId());
		if (roleService.isRootAcsFlag(SysLoginUtil.getLoginUserId())) {
			return sendSmDao.getRecordRoot(params);
		}
		return sendSmDao.getRecordUnit(params);

	}

	@Override
	public SendSm getBySmSeq(String smSeq) {
		return sendSmDao.getBySmSeq(smSeq);
	}

	@Override
	public List getCountByTimeType(Map<String, Object> params) {
		
		params.put("includeToday","no");
		// 默认的话显示前三
		params.put("topN", 3);
		if (params.get("dateType") != null && params.get("dateType").equals("mm")) {
			params.put("preDateParam", "yyyy");
			params.put("dateParam", "yyyy-mm");

			// 没选业务端的话查询top3
			if (params.get("svrNodes").equals("") || params.get("svrNodes") == null) {
				List<String> svrNodes = sendSmDao.getTopMMAndDDByTime(params);
				if(svrNodes.size()<1){
					params.put("svrNodes", null);
				}else{
				params.put("svrNodes", svrNodes);
				}
			} else {
				String[] svrNodes = params.get("svrNodes").toString().split(",");
				params.put("svrNodes", svrNodes);
			}
			
			return sendSmDao.getCountByMM(params);

		}
		if (params.get("dateType") != null && params.get("dateType").equals("dd")) {
			params.put("preDateParam", "yyyy-mm");
			params.put("dateParam", "yyyy-mm-dd");
			String endDate=(String) params.get("endDate");
			String startDate=(String) params.get("startDate");
			if((endDate!=null&&!endDate.equals(""))){
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				
				if(endDate.substring(0,10).equals(format.format(new Date()))){
					params.put("includeToday","yes");
				}			
			}
			
			List<String> svrNodes;
			if (params.get("svrNodes").equals("") || params.get("svrNodes") == null) {
				if(params.get("includeToday").equals("yes")){
					if(endDate!=null&&!endDate.equals("")){
						if(endDate.equals(startDate)){
							 svrNodes = sendSmDao.getTopByTime(params);
						}else{
							 svrNodes = sendSmDao.getTopMMAndDDByTime(params);
						}
						
					}else{
						 svrNodes = sendSmDao.getTopByTime(params);
					}
					
				}else{
					 svrNodes = sendSmDao.getTopMMAndDDByTime(params);

				}	
				if(svrNodes.size()<1){
					params.put("svrNodes", null);
				}else{
				params.put("svrNodes", svrNodes);
				}
				
			} else {
				String[] svrNodess = params.get("svrNodes").toString().split(",");
				params.put("svrNodes", svrNodess);
			}

			return sendSmDao.getCountByDD(params);

		}
		if (params.get("dateType") != null && params.get("dateType").equals("hh24")) {
			params.put("preDateParam", "yyyy-mm-dd");
			params.put("dateParam", "yyyy-mm-dd hh24");
			String endDate=(String) params.get("endDate");
			String preDateInfo=(String) params.get("preDateInfo");
			if((endDate!=null&&!endDate.equals(""))){
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				
				if(endDate.substring(0,10).equals(format.format(new Date()))){
					params.put("includeToday","yes");
				}
				
			}
			if((preDateInfo!=null&&!preDateInfo.equals(""))){
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				
				if(preDateInfo.substring(0,10).equals(format.format(new Date()))){
					params.put("includeToday","yes");
				}
				
			}
			


			if (params.get("svrNodes").equals("") || params.get("svrNodes") == null) {
				List<String> svrNodes;
				if(params.get("includeToday").equals("yes")){
					 svrNodes = sendSmDao.getTopByTime(params);
				}else{
					svrNodes = sendSmDao.getFlowTopByTime(params);
				}
				if(svrNodes.size()<1){
					params.put("svrNodes", null);
				}else{
				params.put("svrNodes", svrNodes);
				}
			} else {
				String[] svrNodes = params.get("svrNodes").toString().split(",");
				params.put("svrNodes", svrNodes);
			}

			return sendSmDao.getCountByHH(params);

		}
		if (params.get("dateType") != null && params.get("dateType").equals("mi")) {
			params.put("preDateParam", "yyyy-mm-dd hh24");
			params.put("dateParam", "yyyy-mm-dd hh24:mi");
			String endDate=(String) params.get("endDate");
			String preDateInfo=(String) params.get("preDateInfo");
			if((endDate!=null&&!endDate.equals(""))){
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				
				if(endDate.substring(0,10).equals(format.format(new Date()))){
					params.put("includeToday","yes");
				}
				
			}
			if((preDateInfo!=null&&!preDateInfo.equals(""))){
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				
				if(preDateInfo.substring(0,10).equals(format.format(new Date()))){
					params.put("includeToday","yes");
				}
				
			}
			
			
			

			if (params.get("svrNodes").equals("") || params.get("svrNodes") == null) {
				List<String> svrNodes;
				if(params.get("includeToday").equals("yes")){
					 svrNodes = sendSmDao.getTopByTime(params);
				}else{
					svrNodes = sendSmDao.getFlowTopByTime(params);
				}
				if(svrNodes.size()<1){
					params.put("svrNodes", null);
				}else{
				params.put("svrNodes", svrNodes);
				}
			} else {
				String[] svrNodes = params.get("svrNodes").toString().split(",");
				params.put("svrNodes", svrNodes);
			}

			return sendSmDao.getCountByMI(params);

		}
		return new ArrayList<>();

	}

	@Override
	public List dealList(List<SendSmCountDTO> list, QueryPage<SendSmCountDTO> qp) {
		if(list.size()<1){
			
			
			ArrayList<Object> finalList = new ArrayList<>();

			finalList.add(CountPage(qp, list.size()));

			HashMap<Object, Object> map = new HashMap<>();
			map.put("svrList", new ArrayList<>());
			map.put("dateList", new ArrayList<>());
			map.put("lists", new ArrayList<>());
			map.put("preDateList", new ArrayList<>());
			map.put("svrNameList", new ArrayList<>());

			finalList.add(map);

			return finalList;
			
		}
		
		
		List<String> svrList = new ArrayList<>();
		ArrayList<Object> dateList = new ArrayList<>();
		ArrayList<Object> preDateList = new ArrayList<>();
		List<String> svrNameList = new ArrayList<>();
		for (SendSmCountDTO dto : list) {
			if (svrList.size() > 0) {
				if (!svrList.contains(dto.getSvrnode())) {
					svrList.add(dto.getSvrnode());
					svrNameList.add(dto.getSvrName());
				}

			} else {

				svrList.add(dto.getSvrnode());
				svrNameList.add(dto.getSvrName());

			}

			if (dateList.size() > 0) {
				if (!dateList.contains(dto.getDateDetail())) {
					preDateList.add(dto.getPreDateInfo());
					dateList.add(dto.getDateDetail());
				}

			} else {
				preDateList.add(dto.getPreDateInfo());
				dateList.add(dto.getDateDetail());

			}

		}
		
		HashMap<Object, Object> midMap = new HashMap<>();
		for(int i=0;i<=svrList.size()-1;i++){		
			midMap.put(svrList.get(i),svrNameList.get(i));	
		}
		Collections.sort(svrList);// 使用Collections的sort方法 
		
		for(int i=0;i<=svrList.size()-1;i++){
			svrNameList.set(i, (String) midMap.get(svrList.get(i)));
		}
		
		ArrayList<ArrayList> lists = new ArrayList<>();
		int flag = 0;
		for (int i = 0; i <= svrList.size() - 1; i++) {

			lists.add(new ArrayList<>());

		}
		SendSmCountDTO smDto = list.get(flag);
		for (int i = 0; i <= dateList.size() - 1; i++) {

			for (int j = 0; j <= svrList.size() - 1; j++) {

				if (smDto.getSvrnode().equals(svrList.get(j)) && smDto.getDateDetail().equals(dateList.get(i))) {

					lists.get(j).add(smDto.getCounts());
					if (flag == list.size() - 1) {
						// 只为执行完代码
						smDto = list.get(0);
					} else {
						flag++;
						smDto = list.get(flag);
					}
				} else {

					lists.get(j).add("0");

				}
			}
		}

		ArrayList<Object> finalList = new ArrayList<>();

		finalList.add(CountPage(qp, list.size()));

		HashMap<Object, Object> map = new HashMap<>();
		map.put("svrList", svrList);
		map.put("dateList", dateList);
		map.put("lists", lists);
		map.put("preDateList", preDateList);
		map.put("svrNameList", svrNameList);

		finalList.add(map);

		return finalList;

	}


	@Override
	public Map<String, Object> querySendMsgPage(Map<String, Object> map) {
		
		List<SendSmDTO> result = null;
		int totalCount = 0;
		map.put("userId", SysLoginUtil.getLoginUserId());
		map.put("start", (Integer.parseInt((String) map.get("pageIndex")) - 1) * Integer.parseInt((String) map.get("pageSize")) + 1);
		map.put("end", Integer.parseInt((String) map.get("pageIndex")) * Integer.parseInt((String) map.get("pageSize")));
		
		map.put("userNo", map.get("receivePhone"));
		map.put("startDate", map.get("startTime"));
		map.put("endDate", map.get("endTime"));
		map.put("svrNode", map.get("account"));
		
		
		Integer limitCount = null;
		if (map.get("limitCount") != null && !"".equals(map.get("limitCount").toString())) {
			limitCount = Integer.valueOf((String) map.get("limitCount"));
		}
		boolean b = false;
		if (limitCount != null && limitCount != -1) {
			totalCount = limitCount;
			map.put("limitCount", limitCount);
			b = true;
		}
		result = sendSmDao.selectRoot(map);
		totalCount = Integer.valueOf(result.size() == 0 ? "0" : result.get(0).getMaxCount());
		HashMap<String, Object> res = new HashMap<String,Object>();
		ArrayList<Object> ssdList = new ArrayList<Object>();
		for (SendSmDTO ssd:result){
			HashMap<String,Object> sdMap = new HashMap<String,Object>();
			sdMap.put("account",ssd.getSvrNode());
			sdMap.put("receivePhone",ssd.getUserNo());
			sdMap.put("content",ssd.getSmContent());
			sdMap.put("creatTime",ssd.getRecvTime());
			sdMap.put("sendTime",ssd.getSendTime());
			sdMap.put("status","0".equals(ssd.getSendCode())?"成功":"失败");
			sdMap.put("errorCount","0".equals(ssd.getSendCode())?0:1);
			ssdList.add(sdMap);
		}
		res.put("totalCount", totalCount);
		res.put("result", ssdList);
		
		
		return res;
	}


	@Override
	public Map<String, Object> selectPageByKeyword(Map<String, Object> map) {
		
		List<SendSmDTO> result = null;
		int totalCount = 0;
		map.put("userId", SysLoginUtil.getLoginUserId());
		map.put("start", (Integer.parseInt((String) map.get("pageIndex")) - 1) * Integer.parseInt((String) map.get("pageSize")) + 1);
		map.put("end", Integer.parseInt((String) map.get("pageIndex")) * Integer.parseInt((String) map.get("pageSize")));
		
		map.put("svrName", map.get("key"));
		map.put("userNo", map.get("key"));
		map.put("smContent", map.get("key"));
		map.put("startDate", map.get("startTime"));
		map.put("endDate", map.get("endTime"));
		Integer limitCount = null;
		if (map.get("limitCount") != null && !"".equals(map.get("limitCount").toString())) {
			limitCount = Integer.valueOf((String) map.get("limitCount"));
		}
		boolean b = false;
		if (limitCount != null && limitCount != -1) {
			totalCount = limitCount;
			map.put("limitCount", limitCount);
			b = true;
		}
		
		result = sendSmDao.selectRootByKeyword(map);
		totalCount = Integer.valueOf(result.size() == 0 ? "0" : result.get(0).getMaxCount());
		HashMap<String, Object> res = new HashMap<String,Object>();
		ArrayList<Object> ssdList = new ArrayList<Object>();
		for (SendSmDTO ssd:result){
			HashMap<String,Object> sdMap = new HashMap<String,Object>();
			sdMap.put("receiver","");
			sdMap.put("phone",ssd.getUserNo());
			sdMap.put("content",ssd.getSmContent());
			sdMap.put("sender",ssd.getSrvName());
			sdMap.put("receiveTime",ssd.getRecvTime());
			sdMap.put("sendTime",ssd.getSendTime());
			sdMap.put("status",ssd.getSendCode());
			sdMap.put("receiveStatus",ssd.getResultCode());
			ssdList.add(sdMap);
		}
		res.put("totalCount", totalCount);
		res.put("result", ssdList);
		
		
		return res;
	}

}
